package com.share.common.tools.xml;

import cn.wanghaomiao.xpath.exception.XpathSyntaxErrorException;
import cn.wanghaomiao.xpath.model.JXDocument;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * XPath语法解析助手
 * Created by er on 2018/1/17.
 */
public class XPathResolveUtil {
    public static final Logger logger = Logger.getLogger(XPathResolveUtil.class);


    /**
     * 解析xml语法 根据xpath
     *
     * @param xpath xpath语法解析
     * @param doc   解析文本
     * @return 文本
     * @deprecated 这种方法解析出来效果不是特别的好
     */
    public static List<String> paserHtmlToText(String xpath, String doc) {
        JXDocument jxDocument = new JXDocument(doc);
        List<String> returnList = new ArrayList<>();
        try {
            List<Object> pasersList = jxDocument.sel(xpath);
            for (Object o : pasersList) {
                if (o instanceof Element) {
                    returnList.add(((Element) o).text());
                }
            }

        } catch (XpathSyntaxErrorException e) {
            logger.error("解析xml文档出错");
            logger.error("解析的文本为---");
            logger.error(doc);
            logger.error("xpath的语法为" + xpath);
            logger.error(e.getMessage());
            logger.error(e.getStackTrace());
            return null;
        }
        return returnList;
    }

    /**
     * 解析文本到Element
     * @param xpath xpath语法解析
     * @param doc 解析文本
     * @return Element
     */
    public static List<Element> paserHtmlToElement(String xpath, String doc) {
        JXDocument jxDocument = new JXDocument(doc);
        List<Element> returnList = new ArrayList<>();
        try {
            List<Object> pasersList = jxDocument.sel(xpath);
            for (Object e : pasersList) {
                if (e instanceof Element) {
                    returnList.add((Element) e);
                }
            }

        } catch (XpathSyntaxErrorException e) {
            logger.error("解析html文本到Element文本出错");
            logger.error("解析的文本为---" + doc);
            logger.error(xpath);
            logger.error("xpath的语法为" + xpath);
            logger.error(e.getMessage());
            logger.error(e.getStackTrace());
            e.printStackTrace();
            return null;
        }
        return returnList;
    }

}
